<?php

class MenuItem
{

  /**
   * @var string
   */
  public $name;

  /**
   * @var mixed
   */
  public $label;

  /**
   * @var mixed
   */
  public $url;

  /**
   * @var string
   */
  public $regex;

  /**
   * @var Menu
   */
  protected $submenu;

  /**
   * Constructor.
   *
   * @param string $name menu item identifier, unique within it's parent menu
   * @param mixed $label the item label or an array with [label, icon]
   * @param mixed $url the url or an array with [url, params]
   * @param string $regex regular expression used to identify when the item is active
   * @param mixed $submenu array or Menu instance
   */
  public function __construct($name, $label, $url, $regex = null, $submenu = null)
  {
    $this->name = $name;
    $this->label = $label;
    $this->url = $url;
    $this->regex = $regex;

    if (is_array($submenu)) {
      $submenu = new Menu($submenu);
    }

    $this->submenu = $submenu;
  }

  public function hasSubmenu()
  {
    return is_a($this->submenu, 'Menu');
  }

  public function getSubmenu()
  {
    if (empty($this->submenu)) {
      $this->submenu = new Menu();
    }

    return $this->submenu;
  }

  public function match($route)
  {
    if (empty($this->regex)) {
      return false;
    }

    return preg_match('#' . $this->regex . '#i', $route);
  }

  public function childMatch($route)
  {
    if (empty($this->submenu)) {
      return false;
    }

    $i = $this->submenu->count() - 1;

    while ($i >= 0 && ! ($this->submenu->getItemAt($i)->match($route) || $this->submenu->getItemAt($i)->childMatch($route)))
      $i --;

    return $i >= 0;
  }

}

?>